package com.cqtczh.qhd.driver.acticity.user;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import tools.L;

import javabeen.Area;
import javabeen.CarRoutHomeBeen;
import javabeen.CarTypeBeen;
import httptools.HttpJsonTool;
import adapter.AreaAdapt;
import adapter.CarRouteANDHomeListAdapter;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
//import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;

import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.cqtczh.qhd.driver.R;
import com.cqtczh.qhd.driver.acticity.base.BaseActivity;
import com.cqtczh.qhd.driver.api.GagApi;

/**
 * @author 作者 E-mail:
 * @date 创建时间：2015-6-5 上午11:12:30
 * @version 1.0
 * @parameter listCountryForMobile.do
 * @since
 * @return
 */
public class CarRoute extends BaseActivity {
	private int Work_id;
	private List<CarRoutHomeBeen> carRoutHomeBeens;
	private ListView listView;
	/**
	 * 司机选择的获得的list
	 */
	private List<Area> serviceDatalist = new ArrayList<Area>();
	
	/**
	 * 常跑地区
	 */
	private int oftenRunCount;
	
	/**
	 * 常驻地区
	 */
	private int oftenStayCount;
	
	
	/**
	 * 常跑是202
	 * 常驻地区201
	 */
	private int work_TYPE;
	/**
	 * 司机能够选择的区域（5个）
	 */
	private HashMap<String, Area> deriverChose = new HashMap<String, Area>();
	/**
	 * 弹出列表的适配器
	 */
	AreaAdapt pop_adapter;
	private AlertDialog.Builder builder;
	private AlertDialog alertDialog;
	// private List<Boolean> flag_list = new ArrayList<Boolean>();
	private String choose;
	private TextView driver_choose;
	/**
	 * 返回的数据
	 */
	private Bundle bundle = new Bundle();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_route_cartype_carhomeactivity);
		Ini();

	}

	private void Ini() {
		// IniDATA();
		Intent intent=getIntent();
		oftenRunCount=intent.getIntExtra("oftenRunCount", 0);
		oftenStayCount=intent.getIntExtra("oftenStayCount", 0);
		work_TYPE=intent.getIntExtra("WORK_TYPE", 0);
		Button upload=(Button) findViewById(R.id.are_upload);
		TextView title = (TextView) findViewById(R.id.head_title);
		title.setText("车辆地区");
		GetData();
		upload.setOnClickListener(new android.view.View.OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				upDrvierReturn();
			}
		});
	}

	private void GetData() {

		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		HashMap<String, String> data = new HashMap<String, String>();
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				if (msg.what == 1) {
					carRoutHomeBeens = (List<CarRoutHomeBeen>) msg.obj;
					IniListView();
				} else {
					Toast.makeText(CarRoute.this, "无网络连接，请检查网络",
							Toast.LENGTH_LONG).show();
				}
			}
		});
		Type type = new TypeToken<List<CarRoutHomeBeen>>() {
		}.getType();
		httpJsonTool.StartWork(data,
		// "http://192.168.1.122:8080/cqtczh/country/listCountryForMobile.do"
				GagApi.CAR_CONTRY, type, null);

	}

	private void IniListView() {
		listView = (ListView) findViewById(R.id.listView1);
		CarRouteANDHomeListAdapter carRouteANDHomeListAdapter = new CarRouteANDHomeListAdapter(
				this, carRoutHomeBeens, R.layout.car_route_home_iteam);
		listView.setAdapter(carRouteANDHomeListAdapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int arg2,
					long arg3) {
				// TODO Auto-generated method stub
				// 弹出选择地区
				GetScondData(carRoutHomeBeens.get(arg2).getCountryid());

			}
		});
	}

	/**
	 * 
	 * @Title: PopAreaList
	 * @Description: TODO(调用的是POP的LISTView)
	 * @param 参数说明
	 *            pop_list_view.xml
	 * @return void 返回类型
	 * @throws
	 */
	private void PopAreaList() {
		// 地区编号

		// 逻辑上的错误只有获得了数据才出来
		if (serviceDatalist.size() <= 0) {
			// dismissLoadingDialog();
			Toast.makeText(this, "该地点即将开始开通", Toast.LENGTH_LONG).show();
			return;
		}

		LayoutInflater inflater = LayoutInflater.from(this);
		View layout = inflater.inflate(R.layout.pop_list_view, null);
		ListView myListView = (ListView) layout.findViewById(R.id.are_listview);
		pop_adapter= new AreaAdapt(this, serviceDatalist,
				R.layout.pop_list_view_iteam);
		myListView.setAdapter(pop_adapter);
		myListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View view, int poisn,
					long arg3) {
				// TODO Auto-generated method stub
				// 弹出选择地区
				//如果已经选择了5个那么就不能让他选择了
				int cut=deriverChose.size();
				if (work_TYPE==201) {
					cut=cut+oftenStayCount;
				}
				if (work_TYPE==202) {
					cut=cut+oftenRunCount;
				}
				if (cut>=5) {
					Toast.makeText(CarRoute.this, "对不起，每名司机只能够选择5个区域",Toast.LENGTH_LONG ).show();
					return;
				}				
				if (serviceDatalist.get(poisn).isFlag()) {
					serviceDatalist.get(poisn).setFlag(false);
					deriverChose.remove(serviceDatalist.get(poisn).getAreaid()+"");
				}else {
					serviceDatalist.get(poisn).setFlag(true);
					deriverChose.put(serviceDatalist.get(poisn).getAreaid()+"", serviceDatalist.get(poisn));
				}
				pop_adapter.notifyDataSetChanged();

			}
		});
		builder = new AlertDialog.Builder(this);

		builder.setTitle(R.id.head_title);
		builder.setView(layout);
		builder.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				// TODO Auto-generated method stub
				arg0.dismiss();
//				for (int i = 0; i < serviceDatalist.size(); i++) {
//					
//				}
//				Intent intent = new Intent(CarRoute.this, MessageActivity.class);
//				intent.putExtras(bundle);
//				CarRoute.this.setResult(1, intent);
//				arg0.dismiss();
				setDataToUI();
				// CarRoute.this.finish();
			}
		});
//		builder.setNegativeButton("取消", new OnClickListener() {
//
//			@Override
//			public void onClick(DialogInterface arg0, int arg1) {
//				// TODO Auto-generated method stub
//				arg0.dismiss();
//			}
//		});
		alertDialog = builder.create();
		alertDialog.show();

	}

	/**
	 * 
	 * @Title: setDataToUI
	 * @Description: TODO(将司机点击的信息显示到UI中)
	 * @param 参数说明
	 * @return void 返回类型
	 * @throws
	 */
	protected void setDataToUI() {
		// TODO Auto-generated method stub
		if (bundle != null) {
			TextView dervierchose = (TextView) findViewById(R.id.dervierchose);
			String str = dervierchose.getText().toString();
			Set<String> keySet = bundle.keySet();
			// String vale = "";
			for (String key : keySet) {
				Area area = ((Area) bundle.getSerializable(key));
				str = str + area.getAreaname() + "、";
			}
			dervierchose.setText(str);
		}
	}

	/**
	 * 
	 * @Title: GetScondData
	 * @Description: TODO(获得2级区域)
	 * @param @param id 参数说明
	 * @return void 返回类型
	 * @throws
	 */
	protected void GetScondData(int id) {
		showLoadingDialog("加载中...");
		HashMap<String, String> data = new HashMap<String, String>();
		data.put("countryid", "" + id);
		HttpJsonTool httpJsonTool = new HttpJsonTool(this);
		httpJsonTool.SetOnLister(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				// TODO Auto-generated method stub
				super.handleMessage(msg);
				// 给flaglist赋值
				dismissLoadingDialog();
				if (msg.what == 1) {
					serviceDatalist.clear();
					List<Area> data = (List<Area>) msg.obj;
					for (int i = 0; i < data.size(); i++) {
						//如果司机选中那么再次打开应该是有选中的状态的
						if (deriverChose.get(data.get(i).getAreaid()+"")!=null) {
							data.get(i).setFlag(true);
							serviceDatalist.add(data.get(i));
						}else {
							serviceDatalist.add(data.get(i));
						}
						
					}
					PopAreaList();
				} else {
					Toast.makeText(CarRoute.this, (String) msg.obj,
							Toast.LENGTH_LONG).show();
				}

			}
		});

		Type type = new TypeToken<List<Area>>() {
		}.getType();
		httpJsonTool.StartWork(data, GagApi.CAR_AREA, type, null);

	}

	
	/**
	 * 
	* @Title: upDrvierReturn 
	* @Description: TODO(upDrvierReturn) 
	* @param   参数说明 
	* @return void    返回类型 
	* @throws
	 */
	private void upDrvierReturn(){
		
		Intent intent = new Intent(CarRoute.this, MessageActivity.class);
		Iterator iterator=deriverChose.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry entry = (Map.Entry) iterator.next();
			String key=(String) entry.getKey();
			Area vaule=(Area) entry.getValue();
			L.v("upDrvierReturn", "upDrvierReturn");
			L.v("vaule", vaule.getAreaname());
			bundle.putSerializable(key, vaule);
		}	
		intent.putExtras(bundle);
		CarRoute.this.setResult(1, intent);
		setDataToUI();
		 CarRoute.this.finish();
		
		
	}
	
}
